package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;


public class YouMiServiceImpl {
	private static Logger logger = Logger.getLogger(YouMiServiceImpl.class);
	public static YouMiServiceImpl service = new YouMiServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.YOUMI_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH =BetweenProperties.YOUMI_ORDERSTATUS_URL;
	private static String YOUMI_KEY =BetweenProperties.YOUMI_KEY;
	private static String YOUMI_CPID =BetweenProperties.YOUMI_CPID;

	
	public String order(String productId,String phoneNo, String cstmOrderNo,String operator,String flowType) {
		String result = "";
		try {
		   
		    String waitSign = YOUMI_CPID+productId+cstmOrderNo+phoneNo+YOUMI_KEY;
		    String sign = EncoderByMd5(waitSign.trim());
		 
			List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
			pairList.add(new BasicNameValuePair("cpId",YOUMI_CPID));
			pairList.add(new BasicNameValuePair("orderNo",cstmOrderNo));
			pairList.add(new BasicNameValuePair("flow",productId));
			pairList.add(new BasicNameValuePair("ChgMobile", phoneNo));
			pairList.add(new BasicNameValuePair("FlowAmount", productId));
			pairList.add(new BasicNameValuePair("phone",phoneNo));
			pairList.add(new BasicNameValuePair("type",operator));
			pairList.add(new BasicNameValuePair("flowType",flowType));
			pairList.add(new BasicNameValuePair("sign",sign));
		   
			String paramStr = "";  
			
			paramStr = EntityUtils.toString(new UrlEncodedFormEntity(pairList,"utf-8")); 
			logger.info("between- 杭州有米订购请求时的参数: " + paramStr);	
			HttpGet httpGet = new HttpGet(HOST_ORDER_PATH+"?"+paramStr);
			CloseableHttpClient client = HttpClients.createDefault();
		
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
			httpGet.setConfig(requestConfig);
		
			HttpResponse response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 杭州有米订购请求时的响应statusCode: " + statusCode);

			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 杭州有米订购请求时的响应数据是: " + result);
			}
	       
		} catch (Exception e) {
			logger.info("bsm- 杭州有米订购请求响应的异常信息:"+e);
			Map<String,String> map = new HashMap<String, String>();
			if (e.getMessage().contains("Read timed out")) {
				map.put("status","1000");
				map.put("statusMessage",e.getMessage());
			}else {
				map.put("status","500");
				map.put("statusMessage",e.getMessage());
			}
			
			result = new Gson().toJson(map);
		}
        
        return result;
		
	}
	
	
	
	public String orderStatus(String cstmOrderNo) {

		String result = "";	
		try {
		
		String waitSign = YOUMI_CPID+cstmOrderNo+YOUMI_KEY;
		String sign = EncoderByMd5(waitSign.toString());
		
		List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
		pairList.add(new BasicNameValuePair("cpId",YOUMI_CPID));
		pairList.add(new BasicNameValuePair("orderNo",cstmOrderNo));
		pairList.add(new BasicNameValuePair("sign",sign));
	
		String paramStr = "";  
		
		paramStr = EntityUtils.toString(new UrlEncodedFormEntity(pairList,"utf-8")); 
		logger.info("between- 杭州有米查询请求时参数: " + cstmOrderNo);
		HttpGet httpGet = new HttpGet(HOST_ORDERSTATUS_PATH+"?"+paramStr);
		CloseableHttpClient client = HttpClients.createDefault();
	
		HttpResponse response = client.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
	    
		logger.info("between- 杭州有米查询请求时的响应statusCode: " + statusCode);
		
		if (200 == statusCode) {
			result = EntityUtils.toString(response.getEntity(), "utf-8");
			logger.info("between- 杭州有米查询请求时的响应数据是: " + result);
	
		}	

		} catch (Exception e) {
			logger.info("bsm- 杭州有米查询请求响应的异常信息:"+e.getMessage()+",该订单号为："+cstmOrderNo);
		}
		return result;
	}
	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String EncoderByMd5(String buf) {  
	    try {  
	        MessageDigest digist = MessageDigest.getInstance("MD5");  
	        byte[] rs = digist.digest(buf.getBytes("UTF-8"));  
	        StringBuffer digestHexStr = new StringBuffer();  
	        for (int i = 0; i < 16; i++) {  
	            digestHexStr.append(byteHEX(rs[i]));  
	        }  
	        return digestHexStr.toString().toUpperCase();  
	    } catch (Exception e) {  
	        logger.error(e.getMessage(), e);  
	    }  
	    return null;  
	  
	}  
	
	public static String byteHEX(byte ib) {  
	    char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
	    char[] ob = new char[2];  
	    ob[0] = Digit[(ib >>> 4) & 0X0F];  
	    ob[1] = Digit[ib & 0X0F];  
	    String s = new String(ob);  
	    return s;  
	}  
	
	public static void main(String[] args) {
		//String resultString = new YouMiServiceImpl().order("199","18566783696","CX2017080210495212","2","2");
		String resultString = new YouMiServiceImpl().orderStatus("CX2017080210495212");
		System.out.println(resultString);
	}
}
